package com.csot.ry.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.csot.common.annotation.Log;
import com.csot.common.core.controller.BaseController;
import com.csot.common.core.domain.AjaxResult;
import com.csot.common.core.page.TableDataInfo;
import com.csot.common.enums.BusinessType;
import com.csot.common.utils.StringUtils;
import com.csot.common.utils.poi.ExcelUtil;
import com.csot.ry.domain.RecordIpPojo;
import com.csot.ry.domain.TRecordSegment;
import com.csot.ry.poi.ExcelUtilSub;
import com.csot.ry.service.impl.TRecordSegmentServiceImpl;
import com.csot.ry.util.CacheKitUtil;
import com.csot.ry.util.UserUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * 备案表Controller
 *
 * @author csot
 * @date 2023-04-06
 */
@RestController
@RequestMapping("/ipmanagement/record")
public class TRecordSegmentController extends BaseController {
    @Autowired
    private TRecordSegmentServiceImpl tRecordSegmentService;

    /**
     * 查询备案表列表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(TRecordSegment tRecordSegment) {
        startPage();
        String city = UserUtils.getCity();
        if (StringUtils.isNotBlank(city)) {
            tRecordSegment.setIpCity(city);
        }
        List<TRecordSegment> list = tRecordSegmentService.selectTRecordSegmentList(tRecordSegment);
        return getDataTable(list);
    }

    /**
     * 导出备案表列表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:record:export')")
    @Log(title = "备案表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TRecordSegment tRecordSegment) {
        String parentId = getLoginUser().getUser().getDept().getParentId() + "";
        if (CacheKitUtil.ip_dept != null && StrUtil.isNotEmpty(parentId) && !"0".equals(parentId)) {
            tRecordSegment.setIpCity(CacheKitUtil.ip_dept.get(parentId + ""));
        }
        List<TRecordSegment> list = tRecordSegmentService.selectTRecordSegmentList(tRecordSegment);
        ExcelUtil<TRecordSegment> util = new ExcelUtil<TRecordSegment>(TRecordSegment.class);
        util.exportExcel(response, list, "备案表数据");
    }

    /**
     * 获取备案表详细信息
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tRecordSegmentService.selectTRecordSegmentById(id));
    }

    /**
     * 新增备案表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:record:add')")
    @Log(title = "备案表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TRecordSegment tRecordSegment) {
        return toAjax(tRecordSegmentService.insertTRecordSegment(tRecordSegment));
    }

    /**
     * 修改备案表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:record:edit')")
    @Log(title = "备案表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TRecordSegment tRecordSegment) {
        return toAjax(tRecordSegmentService.updateTRecordSegment(tRecordSegment));
    }

    /**
     * 删除备案表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:record:remove')")
    @Log(title = "备案表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tRecordSegmentService.deleteTRecordSegmentByIds(ids));
    }

    @Log(title = "城市ip段导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtilSub<TRecordSegment> util = new ExcelUtilSub<TRecordSegment>(TRecordSegment.class);
        List<TRecordSegment> tRecordSegmentList = util.importExcel(file.getInputStream(), 1);
        return toAjax(tRecordSegmentService.importTRecordSegmentList(tRecordSegmentList));
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        try {
            String path = System.getProperty("user.dir");
            path = path + File.separator + "Template" + File.separator + "trecordSegment.xlsx";
            IOUtils.write(Files.readAllBytes(Paths.get(path)), response.getOutputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("下载ip段模块异常", e);
        }
    }

    @PostMapping("/exportrecorduse")
    public AjaxResult exportrecorduse(HttpServletResponse response) {
        new Thread(() -> {
            File file = new File(System.getProperty("user.dir") + "/ytfldb.xlsx");
            try {
                OutputStream outputStream = new FileOutputStream(file);
                List<RecordIpPojo> list = tRecordSegmentService.getDuiBiType("use");
                ExcelUtil<RecordIpPojo> util = new ExcelUtil<>(RecordIpPojo.class);
                util.exportExcel(outputStream, list, "sheet", "用途分类对比数据");
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }).start();
        return toAjax(10);
    }

    @PostMapping("/exportrecordname")
    public AjaxResult exportrecordname(HttpServletResponse response) {
        new Thread(() -> {
            File file = new File(System.getProperty("user.dir") + "/dwmcdb.xlsx");
            try {
                OutputStream outputStream = new FileOutputStream(file);
                List<RecordIpPojo> list = tRecordSegmentService.getDuiBiType("name");
                ExcelUtil<RecordIpPojo> util = new ExcelUtil<>(RecordIpPojo.class);
                util.exportExcel(outputStream, list, "sheet", "单位名称对比数据");
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }).start();
        return toAjax(10);


    }


}
